﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Common.Tools;
using System.Configuration;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using CSP.Common.IProviders;

namespace CSP.Common.Providers
{
    public class SinaApiProvider : OtherApiProvider
    {

        public override string AccessToken
        {
            get
            {
                if (HttpContext.Current.Session["OtherAccessToken"] != null)
                {
                    return HttpContext.Current.Session["OtherAccessToken"].ToString();
                }
                return "";
            }
            set
            {
                HttpContext.Current.Session["OtherAccessToken"] = value;
            }
        }

        /// <summary>
        /// 新浪微博Uid
        /// </summary>
        public string SinaWeiBoUid
        {
            get
            {
                return ConfigurationManager.AppSettings["SinaWeiBoUid"];
            }
        }

        /// <summary>
        /// 新浪AppKey
        /// </summary>
        public string SinaWeiBoAppKey
        {
            get
            {
                return ConfigurationManager.AppSettings["SinaWeiBoAppKey"];
            }
        }

        /// <summary>
        /// 新浪AppSecret
        /// </summary>
        public string SinaWeiBoAppSecret
        {
            get
            {
                return ConfigurationManager.AppSettings["SinaWeiBoAppSecret"];
            }
        }


        /// <summary>
        /// 新浪微博登陆跳转授权
        /// </summary>
        public string SinaWeiBoAuthorizeUri
        {
            get
            {
                return ConfigurationManager.AppSettings["SinaWeiBoAuthorize"];
            }
        }

        /// <summary>
        /// 新浪微博获取获取授权Uri
        /// </summary>
        public string SinaWeiBoAccessTokenUri
        {
            get {
                return ConfigurationManager.AppSettings["SinaWeiBoAccessToken"];
            }
        }

        /// <summary>
        /// 新浪微博授权查询
        /// </summary>
        public string SinaWeiBoGetTokenInfoUri
        {
            get
            {
                return ConfigurationManager.AppSettings["SinaWeiBoGetTokenInfo"];
            }
        }

        /// <summary>
        /// 发布新浪微博
        /// </summary>
        public string SinaWeiBoPublishInfoUri
        {
            get
            {
                return ConfigurationManager.AppSettings["SinaWeiBoPublishInfo"];
            }
        }

        /// <summary>
        /// 关注新浪微博
        /// </summary>
        public string SinaWeiBoAttentionUri
        {
            get
            {
                return ConfigurationManager.AppSettings["SinaWeiBoAttention"];
            }
        }

        /// <summary>
        /// 获取新浪微博用户信息
        /// </summary>
        public string SinaWeiBoUserInfoUri
        {
            get {
                return ConfigurationManager.AppSettings["SinaWeiBoUserInfo"];
            }
        }


        /// <summary>
        /// 营销标题
        /// </summary>
        private string MarketingMsg
        {
            get
            {
                return ConfigurationManager.AppSettings["MarketingMsg"];
            }
        }

        /// <summary>
        /// 营销描述
        /// </summary>
        private string MarketingDescription
        {
            get
            {
                return ConfigurationManager.AppSettings["MarketingDescription"];
            }
        }

        /// <summary>
        /// 用户Id
        /// </summary>
        public override string Uid 
        {
            get
            {

                if (HttpContext.Current.Session["otherUid"] != null)
                {
                    return HttpContext.Current.Session["otherUid"].ToString();
                }
                else
                {
                    return "";
                }

            }
            protected set
            {
                HttpContext.Current.Session["otherUid"] = value;
            }
        }

        /// <summary>
        /// 请求API登陆授权
        /// </summary>
        /// <returns></returns>
        public override void RequestApiAuthorization(string backUrl)
        {

            string requestUrl = SinaWeiBoAuthorizeUri + "?client_id=" + SinaWeiBoAppKey + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(backUrl);
            HttpContext.Current.Response.Redirect(requestUrl);
        }

        /// <summary>
        /// 根据请求的Code值，和重定向的Uri获取用户基本信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="redirectUri"></param>
        /// <returns></returns>
        public override Dictionary<string, string> GetUserInfo(string code, string redirectUri, string openId = "")
        {
            GetAccessToken(code, redirectUri);
            Dictionary<string, string> result = GetUserInfoByAccessToken(AccessToken, Uid);
            return result;
        }

        /// <summary>
        ///Api事件处理管道“关注/微博”
        /// </summary>
        /// <param name="isPublish"></param>
        /// <param name="isAttention"></param>
        public override void EventHandling(bool isPublish, bool isAttention)
        { 
            if(isPublish)
            {
                PublishInfo();
            }

            if (isAttention)
            {
                Attention();
            }
        }

        /// <summary>
        /// 获取权限令牌AccessToken
        /// </summary>
        /// <param name="code">新浪Code</param>
        /// <param name="redirectUri">回调的链接地址</param>
        /// <returns></returns>
        private void GetAccessToken(string code, string redirectUri)
        {
            string redirecturl = "client_id=" + SinaWeiBoAppKey + "&client_secret=" + SinaWeiBoAppSecret + "&grant_type=authorization_code" +
                    "&code=" + code + "&redirect_uri=" + HttpContext.Current.Server.UrlEncode(redirectUri);
            string json = CommonTool.MakePostByUrlAndPostData(SinaWeiBoAccessTokenUri, redirecturl);
            Dictionary<string, string> accessToken = AnalysisSinaAccessToken(json);
            string access_token = accessToken["access_token"];
            AccessToken = access_token;
            Uid = accessToken["uid"];
            
        }

        /// <summary>
        /// 根据AccessToken获取用户信息
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        private Dictionary<string,string> GetUserInfoByAccessToken(string accessToken, string uid)
        {
            string getUserInfoUrl = SinaWeiBoUserInfoUri;
            string redirecturl = getUserInfoUrl + "?access_token=" + accessToken + "&uid=" + uid;
            string json = CommonTool.MakeGetByUrl(redirecturl);
            Dictionary<string, string> result = AnalysisSinaGetUserInfo(json);
            return result;
        }

        

        private void PublishInfo()
        {
            string request;
            string sinaWeiBoPublishInfo = SinaWeiBoPublishInfoUri;
            string marketingMsg = HttpContext.Current.Server.UrlEncode(MarketingMsg+MarketingDescription);
            //request = sinaWeiBoPublishInfo + "?status=" + marketingMsg+"&access_token=" + accessToken ;
            request = "status=" + marketingMsg + "&access_token=" + AccessToken;
            CommonTool.MakePostByUrlAndPostData(sinaWeiBoPublishInfo, request);
        }

        private void Attention()
        {
            string request;
            //关注
            string sinaWeiBoAttention = SinaWeiBoAttentionUri;
            string uid = SinaWeiBoUid;
            request =  "uid=" + uid + "&access_token=" + AccessToken;
            CommonTool.MakePostByUrlAndPostData(sinaWeiBoAttention, request);
        }


        /// <summary>
        /// 解析新浪微博获取授权
        /// </summary>
        /// <param name="json"></param>
        private Dictionary<string, string> AnalysisSinaAccessToken(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //权限token
            string access_token = obj["access_token"].ToString().Replace("\"", "");
            string expires_in = obj["expires_in"].ToString().Replace("\"", "");
            string remind_in = obj["remind_in"].ToString().Replace("\"", "");
            string uid = obj["uid"].ToString().Replace("\"", "");
            dic.Add("access_token", access_token);
            dic.Add("expires_in", expires_in);
            dic.Add("remind_in", remind_in);
            dic.Add("uid", uid);

            return dic;
        }

        /// <summary>
        /// 解析新浪微博查询授权信息
        /// </summary>
        /// <param name="json"></param>
        private Dictionary<string, string> AnalysisSinaGetTokenInfo(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);
            //权限token
            string create_at = obj["create_at"].ToString().Replace("\"", "");
            string scope = obj["scope"].ToString().Replace("\"", "");
            string expires_in = obj["expires_in"].ToString().Replace("\"", "");
            string remind_in = obj["appkey"].ToString().Replace("\"", "");
            string uid = obj["uid"].ToString().Replace("\"", "");
            dic.Add("create_at", create_at);
            dic.Add("scope", scope);
            dic.Add("expires_in", expires_in);
            dic.Add("remind_in", remind_in);
            dic.Add("uid", uid);

            return dic;
        }

        /// <summary>
        /// 解析新浪微博的用户基本信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        private Dictionary<string, string> AnalysisSinaGetUserInfo(string json)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            JObject obj = (JObject)JsonConvert.DeserializeObject(json);

            //用户id
            string id = obj["id"].ToString().Replace("\"", "");
            //用户昵称
            string screen_name = obj["screen_name"].ToString().Replace("\"", "");
            //用户名称
            string name = obj["name"].ToString().Replace("\"", "");
            //用户所在地
            string location = obj["location"].ToString().Replace("\"", "");
            //个人描述
            string description = obj["description"].ToString().Replace("\"", "");
            //用户博客地址
            string url = obj["url"].ToString().Replace("\"", "");
            //用户头像地址
            string profile_image_url = obj["profile_image_url"].ToString().Replace("\"", "");
            //用户微博统一的url地址
            string profile_url = obj["profile_url"].ToString().Replace("\"", "");
            //用户的微号
            string weihao = obj["weihao"].ToString().Replace("\"", "");
            //性别
            string gender = obj["gender"].ToString().Replace("\"", "");
            //用户的大头像
            string avatar_large = obj["avatar_large"].ToString().Replace("\"", "");
            dic.Add("id", id);
            dic.Add("screen_name", screen_name);
            dic.Add("name", name);
            dic.Add("location", location);
            dic.Add("description", description);
            dic.Add("url", url);
            dic.Add("profile_image_url", profile_image_url);
            dic.Add("profile_url", profile_url);
            dic.Add("weihao", weihao);
            dic.Add("gender", gender);
            dic.Add("avatar_large", avatar_large);

            return dic;
        }

        
    }
}
